package com.hyc.sso_server.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component //项目运行时就注入Spring容器
@Slf4j
public class RedisUtils {
    @Resource
    private StringRedisTemplate redis;

    //赋值一个静态的redisTemplate
    public static StringRedisTemplate redisTemplate;

    @PostConstruct //此注解表示构造时赋值
    public void redisTemplate() {
        redisTemplate = this.redis;
    }

    /**
     * @author 冷环渊 Doomwatcher
     * @context:
     * 设置 会过期的 K,V
     * @date: 2022/1/11 18:23
     * @param k
     * @param v
     * @param time
     * @return: boolean
     */
    public static boolean cacheValue(String k, String v, long time) {
        try {
            String key = k;
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            ops.set(key, v);
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Throwable e) {
            log.error("缓存存入失败key:[{}] value:[{}]", k, v);
        }
        return false;
    }

}
